<?php
require_once "Config.php"; 

class Database {
	# $c is the Config object, $r result, $t is db type (mysql/postgresql)
	protected $c, $t;
	public $r;
	
	public function __construct($config = null) {
		if ($config == null)
			$config = new Config();
		
		$this->c = $config;
		$this->t = $config->c['db']['type'];
		$this->connect();
	}
	
	public function result2array($result) {		
		$maxRows = $this->num_rows($result);
		
		if      ($this->t == "mysql")
			for ($i = 0; $i < $maxRows; $i++)
				$array[$i] = mysql_fetch_array($result, MYSQL_ASSOC);
		
		else if ($this->t == "postgresql")
			for ($i = 0; $i < $maxRows; $i++)
				$array[$i] = pg_fetch_assoc($result);
		
		return $array;
	}
	
	# Abstraction functions to support different dbs below
	protected function connect() {
		$config = $this->c->c;
		
		if ($this->t == "mysql") {
			@mysql_connect($config['db']['url'], $config['db']['user'], 
			               $config['db']['pass']) or die("Failed to connect");
			@mysql_select_db($config['db']['db']) or die("Failed to select db");		    
			return true;
		}
		else if ($this->t == "postgresql") {
			# Connection string
			$cStr = "host=".$config['db']['url']
			      ." user=".$config['db']['user']
			      ." password=".$config['db']['pass']
			      ." dbname=".$config['db']['db'];
			@pg_connect($cStr) or die("Failed to select or connect to db");
		}
		
		return false;
	}
	
	protected function query($query) {
		if      ($this->t == "mysql")
			$result = @mysql_query($query);
		else if ($this->t == "postgresql") {
			$result = pg_query($query);
		}
		
		$this->r = $result;
		return $result;
	}
	
	protected function num_rows($set) {
		if ($set == null)
			return false;
		
		if      ($this->t == "mysql")
			return @mysql_num_rows($set);
		else if ($this->t == "postgresql")
			return @pg_num_rows($set);
	}
}
?>
